import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { Row, Col, Card, Form, Icon, Select, Dropdown, Menu, Modal, Divider, message } from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../UserManage.less';
import Check from './check';
import ProjectAfter from './After/createAfter';
import * as option from '../../../common/options';
import { powerBtnFunc } from '@/utils/utils';

const confirm = Modal.confirm;
const Option = Select.Option;

/* eslint react/no-multi-comp:0 */
@connect(({ ProjectManage, loading }) => ({
  ProjectManage,
  loading: loading.models.ProjectManage,
}))
@Form.create()
class ProjectManage extends PureComponent {
  onClick({ key }, record) {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    let _this = this;
    if (key === 'packing' || key === 'edit' || key === 'view') {
      router.push({
        pathname: '/app/project/packing',
        query: {
          projectNo: record.projectNo,
          type: key,
        },
      });
    } else if (key === 'audit') {
      this.setState({
        visibleCheck: true,
        selectedRows: record,
      });
    } else if (key === 'afterEdit') {
      dispatch({
        type: 'ProjectManage/getAfterDetail',
        payload: {
          projectNo: record.projectNo,
        },
        callback(res) {
          if (res.code === 200) {
            _this.handleCreateAfter(true, record);
          }
        },
      });
    } else if (key === 'upper') {
      confirm({
        title: `请确认！`,
        content: `您确定对${record.productName}进行上架吗？`,
        onOk() {
          dispatch({
            type: 'ProjectManage/upper',
            payload: {
              projectNo: record.projectNo,
            },
            callback(res) {
              if (res.code === 200) {
                _this.handleCheck(false, []);
                dispatch({
                  type: 'ProjectManage/fetch',
                  payload: {
                    status: _this.state.status,
                    ...pagination,
                  },
                });
                message.success('上架成功');
              } else {
                message.error(res.errMsg);
              }
            },
          });
        },
      });
    } else if (key === 'under') {
      confirm({
        title: `请确认！`,
        content: `您确定对${record.productName}进行下架吗？`,
        onOk() {
          dispatch({
            type: 'ProjectManage/under',
            payload: {
              projectNo: record.projectNo,
            },
            callback(res) {
              if (res.code === 200) {
                _this.handleCheck(false, []);
                dispatch({
                  type: 'ProjectManage/fetch',
                  payload: {
                    status: _this.state.status,
                    ...pagination,
                  },
                });
                message.success('下架成功');
              } else {
                message.error(res.errMsg);
              }
            },
          });
        },
      });
    } else if (key === 'cancel') {
      confirm({
        title: `请确认！`,
        content: `您确定对${record.productName}进行作废吗？`,
        onOk() {
          dispatch({
            type: 'ProjectManage/cancel',
            payload: {
              projectNo: record.projectNo,
            },
            callback(res) {
              if (res.code === 200) {
                _this.handleCheck(false, []);
                dispatch({
                  type: 'ProjectManage/fetch',
                  payload: {
                    status: _this.state.status,
                    ...pagination,
                  },
                });
                message.success('下架成功');
              } else {
                message.error(res.errMsg);
              }
            },
          });
        },
      });
    } else if (key === 'projectDel') {
      confirm({
        title: `请确认！`,
        content: `您确定对${record.productName}进行流标吗？`,
        onOk() {
          dispatch({
            type: 'ProjectManage/projectDel',
            payload: {
              projectNo: record.projectNo,
            },
            callback(res) {
              if (res.code === 200) {
                _this.handleCheck(false, []);
                dispatch({
                  type: 'ProjectManage/fetch',
                  payload: {
                    status: _this.state.status,
                    ...pagination,
                  },
                });
                message.success('流标成功');
              } else {
                message.error(res.errMsg);
              }
            },
          });
        },
      });
    }
  }

  more(record) {
    const menus = [
      powerBtnFunc(
        '100069',
        <Menu.Item key="packing">
          <a>包装</a>
        </Menu.Item>
      ),
      powerBtnFunc(
        '100071',
        <Menu.Item key="audit">
          <a>审核</a>
        </Menu.Item>
      ),
      powerBtnFunc(
        '100072',
        <Menu.Item key="upper">
          <a>上架</a>
        </Menu.Item>
      ),
      powerBtnFunc(
        '100070',
        <Menu.Item key="edit">
          <a>编辑</a>
        </Menu.Item>
      ),
      powerBtnFunc(
        '100073',
        <Menu.Item key="under">
          <a>下架</a>
        </Menu.Item>
      ),
      powerBtnFunc(
        '100074',
        <Menu.Item key="cancel">
          <a>作废</a>
        </Menu.Item>
      ),
      powerBtnFunc(
        '100114',
        <Menu.Item key="afterEdit">
          <a>投后编辑</a>
        </Menu.Item>
      ),
      <Menu.Item key="none">
        <a>无其他操作</a>
      </Menu.Item>,
      powerBtnFunc(
        '100139',
        <Menu.Item key="projectDel">
          <a>流标</a>
        </Menu.Item>
      ),
    ];
    const menu = (
      <Menu onClick={e => this.onClick(e, record)}>
        {record.status === 1 ? [menus[5], menus[0], menus[6]] : ''}
        {record.status === 2 ? [menus[1], menus[3], menus[5], menus[6]] : ''}
        {record.status === 3 ? [menus[2], menus[6]] : ''}
        {record.status === 4 ? [menus[1], menus[3], menus[5], menus[6]] : ''}
        {record.status === 5 ? [menus[4], menus[6], menus[8]] : ''}
        {record.status === 6 ? [menus[3], menus[6]] : ''}
        {record.status >= 7 ? [menus[6]] : ''}
      </Menu>
    );
    return (
      <Dropdown overlay={menu}>
        <a className="ant-dropdown-link" href="#">
          更多
          <Icon type="down" />
        </a>
      </Dropdown>
    );
  }

  columns = [
    {
      title: '项目编码',
      dataIndex: 'projectNo',
    },

    {
      title: '项目名称',
      dataIndex: 'projectName',
    },
    {
      title: '企业名称',
      dataIndex: 'enterpriseName',
    },
    {
      title: '融资方式',
      dataIndex: 'financeMode',
      render: val => (
        <span>{option.financeMode.map(item => (item.key === val ? item.value : ''))}</span>
      ),
    },
    {
      title: '融资金额',
      dataIndex: 'amount',
    },
    {
      title: '项目期限',
      dataIndex: 'totalDays',
      render: val => <span>{val}天</span>,
    },
    {
      title: '融资类型',
      dataIndex: 'financeType',
      render: val => (
        <span>{option.financeType.map(item => (item.key === val ? item.value : ''))}</span>
      ),
    },
    {
      title: '还款方式',
      dataIndex: 'repayMode',
      render: val => (
        <span>{option.repayMode.map(item => (item.key === val ? item.value : ''))}</span>
      ),
    },

    {
      title: '状态',
      dataIndex: 'status',
      render: val => (
        <span>{option.productStatus.map(item => (item.key === val ? item.value : ''))}</span>
      ),
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          {powerBtnFunc('100068', [
            <a
              key={'view'}
              disabled={record.status === 1}
              onClick={() => this.onClick({ key: 'view' }, record)}
            >
              查看
            </a>,
            <Divider key={'divider'} type="vertical" />,
          ])}

          {this.more(record)}
        </Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      visibleCheck: false,
      visibleCreateAfter: false,
      selectedRows: {},
      searchKey: '',
      pagination: {
        pageNo: 1,
        pageSize: 15,
      },
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'ProjectManage/fetch',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { searchKey } = this.state;
    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
        status: searchKey,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: 15,
      status: searchKey,
    };

    dispatch({
      type: 'ProjectManage/fetch',
      payload: params,
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleCheck = (flag, record) => {
    this.setState({
      visibleCheck: !!flag,
      selectedRows: record,
    });
  };
  handleCreateAfter = (flag, record) => {
    this.setState({
      visibleCreateAfter: !!flag,
      selectedRows: record,
    });
  };
  //审核
  passCheck = (flag, record) => {
    const { dispatch } = this.props;
    const { selectedRows, pagination } = this.state;
    let _this = this;
    dispatch({
      type: 'ProjectManage/ProjectAudit',
      payload: { code: selectedRows.projectNo, ...record },
      callback(res) {
        if (res.code === 200) {
          _this.handleCheck(false, []);
          dispatch({
            type: 'ProjectManage/fetch',
            payload: {
              status: _this.state.status,
              ...pagination,
            },
          });
          message.success('操作成功');
        } else {
          message.error(res.errMsg);
        }
      },
    });
  };

  renderSimpleForm() {
    const { dispatch } = this.props;

    function handleChange(value) {
      dispatch({
        type: 'ProjectManage/fetch',
        payload: {
          status: value,
        },
      });
    }

    return (
      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
        <Col md={8} sm={24}>
          <Select placeholder="请选择状态" style={{ width: 150 }} onChange={handleChange}>
            <Option value={''} key={''}>
              全部
            </Option>
            {option.productStatus.map(item => {
              return (
                <Option value={item.key} key={item.key}>
                  {item.value}
                </Option>
              );
            })}
          </Select>
        </Col>
      </Row>
    );
  }

  render() {
    const {
      ProjectManage: { data },
      loading,
    } = this.props;
    const { selectedRows, visibleCheck, visibleCreateAfter } = this.state;
    const CreateAfterProps = {
      modalVisible: visibleCreateAfter,
      handleOk: this.handleCreateAfter,
      handleCancel: this.handleCreateAfter,
      selectedRows: selectedRows,
    };
    return (
      <PageHeaderWrapper title="标的包装">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data ? data : []}
              rowSelectHide={true}
              rowKey={'projectNo'}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        <Check
          visibleCheck={visibleCheck}
          handleCheck={this.handleCheck}
          passCheck={this.passCheck}
          selectedRows={selectedRows}
        />
        {visibleCreateAfter ? <ProjectAfter {...CreateAfterProps} /> : ''}
      </PageHeaderWrapper>
    );
  }
}

export default ProjectManage;
